package com.czh.oss.controller;

import com.czh.oss.adapter.FileService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;


/**
 * 存储服务接口
 *
 * @author caozaihui
 * @version 1.0
 * @since 2024/8/17 上午 1:23
 */
@RestController
@Slf4j
public class FileController {
    @Resource
    private FileService fileService;

    @PostMapping("upload")
    public String uploadFile(@RequestParam("uploadFile") MultipartFile uploadFile,
                             @RequestParam("bucket")  String bucket,
                             @RequestParam(value = "objectName", required = false) String objectName) {
        // 参数校验
        if (uploadFile == null || bucket == null || bucket.trim().isEmpty() ) {
            throw new IllegalArgumentException("MultipartFile, bucketName and objectName cannot be null or empty.");
        }
        try {
            // 执行文件上传操作
            String originalFilename = uploadFile.getOriginalFilename();
            String fileType = Objects.requireNonNull(originalFilename).substring(originalFilename.lastIndexOf("."));
            if (Objects.isNull(objectName)){
                Date date = new Date();
                objectName = date.getTime()+fileType;
            }else {
                objectName = objectName+fileType;
            }

            return fileService.uploadObject(uploadFile, bucket, objectName);
        } catch (Exception e) {
            throw new RuntimeException("Failed to upload file to OSS.", e);
        }
    }
}
